﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography.X509Certificates;
using OestsCommon.Model;

namespace OestsDataBase
{
    public static class PostDAL
    {
        //岗位
        public static void CreateTable()
        {
            string sqlCheck = "if object_id( 'T_Post') is not null select 1 else select 0";
            if ((int)SqlHelper.ExecuteScalar(sqlCheck) == 0)
            {
                string sqlCreacte = @"CREATE TABLE T_Post (id bigint primary key ,name NVARCHAR(MAX) not null)";

                SqlHelper.ExecuteNonQuery(sqlCreacte);
            }
        }
        public static List<PostModel> GetAllProjectPost()
        {
            List<string> listTable = SqlHelper.GetTableListByType("T_Post_");
            List<PostModel> listAllData = new List<PostModel>();
            foreach (var item in listTable)
            {
                List<PostModel> list = GetDataByTableName(item);
                if (list != null)
                {
                    listAllData.AddRange(list);
                }
            }
            return listAllData;
        }

        private static List<PostModel> GetDataByTableName(string tabelName)
        {
            string strSql = string.Format("select * from {0} ", tabelName);
            List<PostModel> list = new List<PostModel>();
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt == null) { return null; }
            foreach (DataRow dr in dt.Rows)
            {
                PostModel s = ReadData(dr);
                list.Add(s);
            }
            return list;
        }

        private static PostModel ReadData(DataRow dr)
        {
            PostModel model = new PostModel();
            model.Id = Int32.Parse(dr["id"].ToString());
            model.Name = dr["name"].ToString();
            model.ProjectId = Int32.Parse(dr["project_id"].ToString());
            model.NeedInventory = bool.Parse(dr["needInventory"].ToString());
            return model;
        }


        public static List<PostModel> GetData(int projectId)
        {
            List<PostModel> list = new List<PostModel>();
            string strSql = "select * from T_Post_" + projectId;
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt == null) { return null; }
            foreach (DataRow dr in dt.Rows)
            {
                PostModel model = ReadData(dr);
                list.Add(model);
            }
            return list;
        }

        public static PostModel GetPostModel(int projectId, int postId)
        {
            List<PostModel> list = GetData(projectId);
            foreach (var postModel in list)
            {
                if (postModel.Id == postId)
                    return postModel;
            }
            return null;
        }

    }
}
